var io = require('socket.io-client');
var http = require('http');
var reqCache = {};

function startProxy (host, port, server) {
  var websocket = io.connect(server);

  websocket.on('connect', function () {
    console.log('connected');
    websocket.emit('auth', 'socket.io.password');

    websocket.on('success', function (data) {
      if (data === true) {
        console.log('Pass Auth. Start Proxy');
        websocket.on('request', function (data) {
          var req = http.request({
            headers: data.headers,
            method: data.method,
            path: data.url,
            hostname: host,
            port: port
          }, function (res) {
            var buffers = [];
            var countLen = 0;
            res.on('data', function (chunk) {
              buffers.push(chunk);
              countLen += chunk.length;
            });

            res.on('end', function () {
              var result;
              if (buffers.length === 0) {
                result = new Buffer(0)
              } else if (buffers.length === 1) {
                result = buffers[0];
              } else {
                result = new Buffer(countLen);
                for (var i = 0, pos = 0, l = buffers.length; i < l; i++) {
                  var chunk = buffers[i];
                  chunk.copy(result, pos);
                  pos += chunk.length;
                }
              }

              websocket.emit('response', {
                id: data.id,
                status: res.statusCode,
                headers: res.headers,
                body: result.toString('hex')
              });
            });

            res.on('error', function (err) {
              console.log(err);
              websocket.emit('response', {
                status: 200,
                body: {success: false, msg: 'Proxy RES ERROR'},
                id: data.id
              });
            })
          });
          reqCache[data.id] = req;

          req.on('error', function (err) {
            console.log(err);
            websocket.emit('response', {
              status: 200,
              body: {success: false, msg: 'Proxy REQ ERROR'},
              id: data.id
            });
          });

        });

        websocket.on('data', function (reqData) {
          reqCache[reqData.id].write(reqData.data);
        });

        websocket.on('end', function (id) {
          reqCache[id].end();
          reqCache[id] = null;
        });
      }
    });
  });
}

module.exports = startProxy;